<template>
  <el-dialog
    v-model="open" title="预留付款" width="800px" append-to-body :close-on-click-modal="false"
    @close="cancel"
  >
    <el-form ref="reservationRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="场地/时间">
        <el-tag
          v-for="(tag,index) in form.orderList"
          :key="index" style="height: auto;padding: 10px;"
          class="checkedPlace"
        >
          {{ tag.siteName }}:
          <br>
          {{ tag.orderTime.split(',').join('-') }}
        </el-tag>
      </el-form-item>

      <el-form-item label="预订人员">
        <el-radio-group v-model="form.orderPersonType" @change="changePersonType">
          <el-radio label="1">散客</el-radio>
          <el-radio label="0">会员</el-radio>
        </el-radio-group>

        <el-button v-if="form.orderPersonType=='0'" class="ml20" type="text" @click="openMemberList">+选择会员</el-button>
      </el-form-item>
      <el-form-item label="价格">
        <span class="cRed">￥{{ form.totalPrice }}</span>
      </el-form-item>
      <el-form-item v-if="form.memberCardCode" label="会员价:">
        <span class="cRed">￥{{ form.memberPrice }}</span>
      </el-form-item>
      <el-form-item v-if="form.memberCardCode && form.payType=='2'" label="折扣价:">
        <span class="cRed">￥{{ form.discountPrice }}</span>
      </el-form-item>
      <el-form-item v-if="form.orderPersonType=='0'" label="会员卡号" prop="memberCardCode">
        <el-input v-model="form.memberCardCode" readonly />
      </el-form-item>
      <el-form-item label="预订人" prop="orderPersonName">
        <el-input v-model="form.orderPersonName" placeholder="预订人姓名" />
      </el-form-item>
      <el-form-item label="电话" prop="orderPersonTel">
        <el-input v-model="form.orderPersonTel" type="number" placeholder="预订人电话" />
      </el-form-item>
      <el-form-item label="支付价格" prop="finalPrice">
        <el-input v-model="form.finalPrice" type="number" placeholder="支付价格(可修改)" />
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-radio-group v-model="form.payType" @change="changePayType">
          <el-radio label="0" border>扫码</el-radio>
          <el-radio label="1" border>现金</el-radio>
          <el-radio v-if="form.orderPersonType=='0'" label="2" border>余额</el-radio>
          <el-radio label="3" border>银联</el-radio>
          <el-radio label="4" border>支付宝</el-radio>
          <el-radio label="5" border>微信</el-radio>
          <el-radio label="6" border>其他</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="订单备注">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="warning" @click="submitForm('0')">付款（￥{{ form.finalPrice }}）</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <!--选择会员-->
  <SelectMember v-model="openMember" @chooseMember="chooseMember" />
</template>

<script setup>
import { getCurrentInstance, reactive } from '@vue/runtime-core'
import { toRefs } from '@vueuse/shared'
import { validPhone } from '@/utils/validate'
import { getGenerdatePrice, backYuLiuPay, backGetInfo } from '@/api/ven/reserve'
import { watch } from 'vue'
import SelectMember from './selectMember'


const { proxy } = getCurrentInstance()
const emit = defineEmits(['submitForm'])

const props = defineProps({
  props: {
    type: Object,
    default: () => ({
      open: false,
      data: {}
    })
  }
})

const formBase = {
  memberCardCode: '', // 会员卡号
  submitType: '1', // 0 直接付款 1 预定场地
  fucType: '0', // 0 场地预定 1 预留
  orderType: '2', // 0 普通预定 1 长租预定 2 预留 3 锁场
  orderPersonType: '1',
  payType: '', // 0 扫码 1 现金 2 余额 3 银联  4 支付宝 5 微信 6 其他
  orderList: []
}
const data = reactive({
  form: {
    ...formBase
  },
  rules: {
    memberCardCode: {
      validator: (rule, value, callback) => {
        if (form.value.orderPersonType === '0') {
          if (!value) {
            callback('必填')
            return
          }
        }
        callback()
      }, required: true },
    orderPersonName: { required: true, message: '必填', trigger: 'blur' },
    orderPersonTel: [{ required: true, message: '必填', trigger: 'blur' }, {
      validator: (rule, value, callback) => {
        if (!validPhone(value)) {
          callback('手机号码错误')
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }],
    finalPrice: [{ required: true, message: '必填', trigger: 'blur' }, {
      validator: (rule, value, callback) => {
        if (parseFloat(value) < 0) {
          callback('价格有误')
          return
        }
        callback()
      },
      trigger: 'blur'
    }],
    payType: {
      validator: (rule, value, callback) => {
        if (form.value.submitType === '0') {
          if (!value) {
            callback('必填')
            return
          }
        }
        callback()
      }, required: true, trigger: 'change' }
  },
  openMember: false
})
const { form, rules, openMember } = toRefs(data)

const { open } = toRefs(props.props)

watch(open, (val) => {
  if (val) {
    backGetInfo(props.props.data.id).then(res => {
      // 获取父订单信息
      form.value = res.data
      form.value.yuLiuOrderId = res.data.id
      form.value.fucType = '0'
      form.value.orderList = []
      if (form.value.parentType == '0') {
        form.value.orderList = [{
          siteName: form.value.siteName,
          siteId: form.value.siteId,
          orderTime: form.value.orderTimePeriod,
          orderDate: form.value.orderDate
        }]
        getPriceArr()
      } else {
        for (var s of form.value.sonList) {
          var jj = {
            siteName: s.siteName,
            siteId: s.siteId,
            orderTime: s.orderTimePeriod,
            orderDate: s.orderDate
          }
          form.value.orderList.push(jj)
        }
        getPriceArr()
      }
    })
  } else {
    proxy.resetForm('reservationRef')
    form.value.orderList = []
  }
})

function getPriceArr() {
  getGenerdatePrice(form.value.orderList, form.value.memberCardCode, form.value.payType).then(res => {
    let nomalPrice = 0
    let memberPrice = 0
    let discountPrice = 0

    _.each(res.data[0], (o) => {
      nomalPrice += parseFloat(o)
    })
    _.each(res.data[1], (o) => {
      memberPrice += parseFloat(o)
    })
    _.each(res.data[2], (o) => {
      discountPrice += parseFloat(o)
    })
    //   nomalPrice = parseFloat(_.sum(res.data[0]))
    //   memberPrice += parseFloat(_.sum(res.data[1]))
    //   discountPrice += parseFloat(_.sum(res.data[2]))


    form.value.totalPrice = nomalPrice.toFixed(2)
    form.value.memberPrice = memberPrice.toFixed(2)
    form.value.discountPrice = discountPrice.toFixed(2)
    if (form.value.orderPersonType == '1') {
      form.value.finalPrice = form.value.orderAmount
    } else {
      if (form.value.payType === '2') {
        form.value.finalPrice = form.value.discountPrice
      } else {
        form.value.finalPrice = form.value.memberPrice
      }
    }
  })
}

function changePayType() {
  // 切换支付方式时，重新获取价格
  if (form.value.memberCardCode) {
    if (form.value.payType == '2') {
      form.value.finalPrice = form.value.discountPrice
    } else {
      form.value.finalPrice = form.value.memberPrice
    }
  }
}

function changePersonType() {
  if (form.value.orderPersonType === '0') {
    form.value.payType = '2'
    form.value.orderPersonName = ''
    form.value.orderPersonTel = ''
  } else {
    form.value.payType = ''
    form.value.memberCardCode = ''
    form.value.orderPersonName = ''
    form.value.orderPersonTel = ''

    getPriceArr()
  }
}


function submitForm(type) {
  form.value.submitType = type
  proxy.$refs['reservationRef'].validate((valid) => {
    if (valid) {
      proxy.$modal.confirm('确定付款？')
        .then(() => {
          backYuLiuPay(form.value).then(() => {
            proxy.$modal.msgSuccess('操作成功')
            open.value = false
            emit('submitForm')
          })
        })
    }
  })
}

function cancel() {
  open.value = false
}

function openMemberList() {
  openMember.value = true
}

// 选择会员
function chooseMember(member) {
  form.value.memberCardCode = member.cardCode
  form.value.orderPersonName = member.memberName
  form.value.orderPersonTel = member.memberTelno
  form.value.payType = '2'
  getPriceArr()
}

</script>

<style scoped>

</style>
